﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;

namespace Uranus.Common
{
    public class ImageCommon
    {
        //将image转化为二进制 
        public static byte[] GetByteImage(Image img)
        {

            byte[] bt = null;

            if (!img.Equals(null))
            {
                using (MemoryStream mostream = new MemoryStream())
                {
                    Bitmap bmp = new Bitmap(img);

                    bmp.Save(mostream, System.Drawing.Imaging.ImageFormat.Jpeg);//将图像以指定的格式存入缓存内存流

                    bt = new byte[mostream.Length];

                    mostream.Position = 0;//设置留的初始位置

                    mostream.Read(bt, 0, Convert.ToInt32(bt.Length));
                }

            }
            return bt;

        }
        /// <summary>
        /// 读取byte[]并转化为图片
        /// </summary>
        /// <param name="bytes">byte[]</param>
        /// <returns>Image</returns>
        public static Image GetImageByBytes(byte[] bytes)
        {
            Image photo = null;
            using (MemoryStream ms = new MemoryStream(bytes))
            {
                ms.Write(bytes, 0, bytes.Length);
                photo = Image.FromStream(ms, true);
            }
            return photo;
        }

        /// <summary>
        /// 图片裁切
        /// widthratio、heightratio宽高比例 8 11
        /// </summary>
        public static byte[] CutPic(int widthratio, int heightratio, Stream stream)
        {
            Image img = new Bitmap(stream);
            int width = 0, height = 0, x = 0, y = 0;
            Image newimg = null;
            Graphics g = null;
            double cWidth = img.Width / widthratio, cHeight = img.Height / heightratio;
            if (cWidth == cHeight) return Common.ImageCommon.GetByteImage(img);
            //定位
            Rectangle fromr = new Rectangle(0, 0, 0, 0);//原图裁剪定位
            Rectangle tor = new Rectangle(0, 0, 0, 0);//目标定位
            //宽高按比例裁切
            if (cWidth > cHeight)
            {
                height = img.Height;//高度不变
                width = (int)(widthratio * cHeight);//裁切后的宽度
                newimg = new Bitmap(width, height);

                fromr.X = (img.Width - width) / 2;//裁切位置
                fromr.Y = 0;
                fromr.Width = width;
                fromr.Height = height;

                tor.X = 0;
                tor.Y = 0;
                tor.Width = width;
                tor.Height = height;

            }
            else
            {
                width = img.Width;//宽度不变
                height = (int)(cWidth * heightratio);//裁切后的高度
                newimg = new Bitmap(width, height);

                fromr.X = 0;//裁切位置
                fromr.Y = (img.Height - height) / 2;
                fromr.Width = width;
                fromr.Height = height;

                tor.X = 0;
                tor.Y = 0;
                tor.Width = width;
                tor.Height = height;
            }
            //把图片写到画板里面
            g = Graphics.FromImage(newimg);
            //把第二个Ractangle的x,y,width,height覆盖到第一个0,0,width,height的位置来画
            g.DrawImage(img, tor, fromr, GraphicsUnit.Pixel);
            g.Dispose();
            return Common.ImageCommon.GetByteImage(newimg);
        }

        /// <summary>
        /// 根据上传文件获取Image 按照固定宽度等比缩
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="width"></param>
        /// <param name="savePath"></param>
        /// <param name="flag"></param>
        /// <returns></returns>
        public static Image GetImageUplaodPhoto(Stream stream, int width, string savePath)
        {
            Image image = Image.FromStream(stream, true);
            double height = Math.Floor(width * 1.00 / image.Width * image.Height);

            using (Bitmap bm = new Bitmap(width, (int) height))
            {
                using (Graphics graphics = Graphics.FromImage(bm))
                {
                    //设置质量
                    graphics.CompositingQuality = CompositingQuality.HighQuality;
                    graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    graphics.DrawImage(image, new Rectangle(0, 0, bm.Width, bm.Height), new Rectangle(0, 0, image.Width, image.Height), System.Drawing.GraphicsUnit.Pixel);
                }
                if (string.IsNullOrEmpty(savePath))
                {
                    return bm;
                }
                if (savePath.StartsWith("/"))
                {
                    savePath = HttpContext.Current.Server.MapPath(savePath);
                }

                string directory = GetFileDirectoryByFile(savePath);
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                EncoderParameters ep = new EncoderParameters();
                long[] qy = new long[1];
                qy[0] = 100;//设置压缩的比例1-100
                EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
                ep.Param[0] = eParam;
                ImageCodecInfo jpegICIinfo = GetImageCodecInfo("image/jpeg");
                if (jpegICIinfo != null)
                {
                    bm.Save(savePath, jpegICIinfo, ep);
                }
                else
                {
                    bm.Save(savePath, image.RawFormat);
                }
            }
            return new Bitmap(savePath);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static string GetFileDirectoryByFile(string filePath)
        {
            if (string.IsNullOrEmpty(filePath))
            {
                throw new ArgumentNullException(filePath, "文件路径为空");
            }

            int frist = filePath.LastIndexOf("\\");
            return filePath.Substring(0, frist);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="mimeType"></param>
        /// <returns></returns>
        private static ImageCodecInfo GetImageCodecInfo(string mimeType)
        {
            ImageCodecInfo[] codecInfo = ImageCodecInfo.GetImageEncoders();
            foreach (ImageCodecInfo ici in codecInfo)
            {
                if (ici.MimeType == mimeType) return ici;
            }
            return null;
        }

    }
}
